from typing import Annotated
from sqlalchemy.orm import Session
from fastapi import APIRouter, Depends, HTTPException , status, Path
from models import Todos , User
from database import sessionmaker
from pydantic import BaseModel , Field
from .auth import get_current_user
from passlib.context import CryptContext


SessionLocal = sessionmaker


router = APIRouter(
    prefix="/user",
    tags=["user"],
)

# 定义获取数据库会话的依赖函数
def get_db():
    # 创建新的数据库会话
    db = SessionLocal()
    try:
        # 使用yield返回数据库会话
        yield db
    finally:
        # 确保在请求结束时关闭数据库会话
        db.close()

# 创建类型注解的数据库依赖项，用于FastAPI的依赖注入系统
db_dependency = Annotated[Session, Depends(get_db)]

user_dependency = Annotated[dict, Depends(get_current_user)]
bcypt_context = CryptContext(schemes=["bcrypt"], deprecated="auto")

class UserVerification(BaseModel):
    password: str
    new_password: str = Field(min_length=6)

    


@router.get("/", status_code=status.HTTP_200_OK)
async def get_user(user: user_dependency, db: db_dependency):
    if user is None:
        raise HTTPException(status_code=401, detail="Authentication Failed")
    return db.query(User).filter(User.id == user.get("id")).first()

@router.put("/password", status_code=status.HTTP_204_NO_CONTENT)
async def change_password(user: user_dependency, db: db_dependency,
                          user_verification: UserVerification):
    if user is None:
        raise HTTPException(status_code=401, detail='Authentication Failed')
    user_model = db.query(User).filter(User.id == user.get('id')).first()

    if not bcypt_context.verify(user_verification.password, user_model.hashed_password):
        raise HTTPException(status_code=401, detail='Error on password change')
    user_model.hashed_password = bcypt_context.hash(user_verification.new_password)
    db.add(user_model)
    db.commit()